// pages/menu/menu.js
Page({
  data: {
    accelerometerX: 0,
    accelerometerY: 0,
    accelerometerZ: 0,
    pitch: 0,
    roll: 0,
    yaw: 0,
    ballX: 100,
    ballY: 100,
    historyX: [],
    historyY: [],
    historyZ: [],
    maxHistoryLength: 100, // 可根据需要调整历史数据长度
    refreshRate: 50 // 假设刷新率为 50Hz
  },
  // 定义滤波系数
  filterAlpha: 0.7,
  // 存储上一次的加速度和姿态角数据
  lastAccelerometerX: 0,
  lastAccelerometerY: 0,
  lastAccelerometerZ: 0,
  lastPitch: 0,
  lastRoll: 0,
  onLoad() {
    this.startAccelerometer();
    this.startCompass();
  },
  startAccelerometer() {
    wx.startAccelerometer({
      success: () => {
        console.log('重力加速度传感器启动成功');
        wx.onAccelerometerChange((res) => {
          const rawX = res.x;
          const rawY = res.y;
          const rawZ = res.z;

          // 对三轴加速度数据应用一阶低通滤波
          const x = this.filterAlpha * rawX + (1 - this.filterAlpha) * this.lastAccelerometerX;
          const y = this.filterAlpha * rawY + (1 - this.filterAlpha) * this.lastAccelerometerY;
          const z = this.filterAlpha * rawZ + (1 - this.filterAlpha) * this.lastAccelerometerZ;

          // 更新上一次的加速度数据
          this.lastAccelerometerX = x;
          this.lastAccelerometerY = y;
          this.lastAccelerometerZ = z;

          // 计算原始的 pitch 和 roll 值
          const rawPitch = Math.atan2(-y, Math.sqrt(x * x + z * z)) * (180 / Math.PI);
          const rawRoll = Math.atan2(x, Math.sqrt(y * y + z * z)) * (180 / Math.PI);

          // 对 pitch 和 roll 数据应用一阶低通滤波
          const pitch = this.filterAlpha * rawPitch + (1 - this.filterAlpha) * this.lastPitch;
          const roll = this.filterAlpha * rawRoll + (1 - this.filterAlpha) * this.lastRoll;

          // 更新上一次的 pitch 和 roll 值
          this.lastPitch = pitch;
          this.lastRoll = roll;

          // 根据 pitch 和 roll 计算小球位置
          const radius = 120;
          const centerX = 100;
          const centerY = 100;
          const ballX = centerX + radius * (roll / 90);
          const ballY = centerY + radius * (pitch / 90);

          // 更新历史数据
          let historyX = this.data.historyX;
          let historyY = this.data.historyY;
          let historyZ = this.data.historyZ;
          historyX.push(x);
          historyY.push(y);
          historyZ.push(z);

          // 控制历史数据长度
          if (historyX.length > this.data.maxHistoryLength) {
            historyX.shift();
            historyY.shift();
            historyZ.shift();
          }

          this.setData({
            accelerometerX: x.toFixed(2),
            accelerometerY: y.toFixed(2),
            accelerometerZ: z.toFixed(2),
            pitch: pitch.toFixed(2),
            roll: roll.toFixed(2),
            ballX,
            ballY,
            historyX,
            historyY,
            historyZ
          });

          // 绘制曲线
          this.drawAccelerationChart();
        });
      },
      fail: (err) => {
        console.error('重力加速度传感器启动失败', err);
      }
    });
  },
  startCompass() {
    wx.startCompass({
      success: () => {
        console.log('磁力计启动成功');
        wx.onCompassChange((res) => {
          const compassHeading = res.direction;
          this.setData({
            yaw: compassHeading.toFixed(2)
          });
        });
      },
      fail: (err) => {
        console.error('磁力计启动失败', err);
      }
    });
  },
  drawAccelerationChart() {
    const ctx = wx.createCanvasContext('accelerationChart');
    const { historyX, historyY, historyZ, maxHistoryLength, refreshRate } = this.data;
    const query = wx.createSelectorQuery();
    query.select('.acceleration-chart').boundingClientRect();
    query.exec((res) => {
      const canvasWidth = res[0].width;
      const canvasHeight = res[0].height;
      const stepX = canvasWidth / maxHistoryLength;

      // 清空画布
      ctx.clearRect(0, 0, canvasWidth, canvasHeight);

      // 绘制 X 轴加速度曲线
      ctx.beginPath();
      ctx.strokeStyle = 'red';
      historyX.forEach((value, index) => {
        const x = index * stepX;
        const y = canvasHeight - (value + 1) * canvasHeight / 2; // 简单映射到画布高度
        if (index === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      });
      ctx.stroke();

      // 绘制 Y 轴加速度曲线
      ctx.beginPath();
      ctx.strokeStyle = 'green';
      historyY.forEach((value, index) => {
        const x = index * stepX;
        const y = canvasHeight - (value + 1) * canvasHeight / 2;
        if (index === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      });
      ctx.stroke();

      // 绘制 Z 轴加速度曲线
      ctx.beginPath();
      ctx.strokeStyle = 'blue';
      historyZ.forEach((value, index) => {
        const x = index * stepX;
        const y = canvasHeight - (value + 1) * canvasHeight / 2 - 50;
        if (index === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      });
      ctx.stroke();

      // // 绘制刷新率文本
      // ctx.font = '16px Arial';
      // ctx.fillStyle = 'black';
      // ctx.textAlign = 'right';
      // ctx.fillText(`刷新率: ${refreshRate}Hz`, canvasWidth - 10, 20);

      // 绘制完成
      ctx.draw();
    });
  },
  onUnload() {
    wx.stopAccelerometer({
      success: () => {
        console.log('重力加速度传感器停止监听');
      },
      fail: (err) => {
        console.error('重力加速度传感器停止监听失败', err);
      }
    });
    wx.stopCompass({
      success: () => {
        console.log('磁力计停止监听');
      },
      fail: (err) => {
        console.error('磁力计停止监听失败', err);
      }
    });
  },
  vibrateShort: function () {
    wx.vibrateShort({
      success: function () {
        console.log('短震动成功');
      },
      fail: function (err) {
        console.error('短震动失败', err);
      }
    });
  },
  vibrateLong: function () {
    wx.vibrateLong({
      success: function () {
        console.log('长震动成功');
      },
      fail: function (err) {
        console.error('长震动失败', err);
      }
    });
  }
});